package be.bonamis.umpire.ui.client.mvp.impl;

import java.util.ArrayList;
import java.util.List;

import be.bonamis.projects.umpire.business.dto.UmpireDTO;
import be.bonamis.umpire.ui.client.mvp.WhoView;
import be.bonamis.umpire.ui.client.resources.Resources;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.inject.Inject;

public class WhoViewImpl extends Composite implements WhoView {

	private UmpireDTO umpire;
	private Presenter presenter;	

	@UiField
	Label lastName;

	@UiField
	Label firstName;

	@UiField
	Label city;

	@UiField
	Label email;

	@UiField
	Label gsm;

	@UiField
	Label club;

	@UiField
	Label birthDate;

	@UiField
	Label ranking;
	
	@UiField
	SimplePanel simplePanel;

	@UiField(provided = true)
	SuggestBox umpireSuggestBox;	
	
	@UiField
    FormPanel uploadForm;
	
	@UiField
	Hidden hiddenumpireId;	
	
	@UiField
    Button uploadButton; 
 
    @UiField
    FileUpload uploadField;
	
    @UiField
	Anchor dispoButton;
	
	@UiField
	Anchor whoButton;
	
	@UiField
	Anchor quizButton;
	
	@UiField
	Anchor historyButton;
	
	@UiField
	Label fullName;	
	
	@UiHandler("dispoButton")
	public void onClickDispo(ClickEvent event) {
		presenter.dispoButtonClicked();
	}
	
	@UiHandler("whoButton")
	public void onClickWho(ClickEvent event) {
		presenter.whoButtonClicked();
	}
	
	@UiHandler("quizButton")
	public void onClickQuiz(ClickEvent event) {
		presenter.quizButtonClicked();
	}
	
	@UiHandler("historyButton")
	public void onClickHistory(ClickEvent event) {
		presenter.historyButtonClicked();
	}
	
	@UiHandler("uploadButton")
    void onSubmit(ClickEvent event) {
		uploadField.getFilename();		
        uploadForm.submit();
    }

	interface WhoViewImplUiBinder extends UiBinder<HTMLPanel, WhoViewImpl> {
	}
	
	private DynamicSuggestOracle oracle = new DynamicSuggestOracle();

	@Inject
	public WhoViewImpl(WhoViewImplUiBinder uiBinder, final Resources resources) {
		umpireSuggestBox = new SuggestBox(oracle);		

		initWidget(uiBinder.createAndBindUi(this));
		resources.css().ensureInjected();
		postInit();
		//Integer test = umpire.getId();
		
		//uploadForm.setMethod(FormPanel.METHOD_POST);
	    //The HTTP request is encoded in multipart format. 
	    uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART); //  multipart MIME encoding
	    //uploadForm.setAction("/FileUploadGreeting"); // The servlet FileUploadGreeting	     
	    
	    //uploadField.setName("uploader"); // Very important
		
		umpireSuggestBox.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (KeyCodes.KEY_ENTER != event.getNativeKeyCode()) {
					if (umpireSuggestBox.getText().length() >= 2) {
						presenter.searchUmpires(umpireSuggestBox.getText());
					}
				}
			}
		});
		
		uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
			 
            @Override
            public void onSubmitComplete(SubmitCompleteEvent event) {            	
            	presenter.getUmpireById(umpire.getId());
//            	Image image = new Image(umpire.getImageData());
//    			image.setHeight("250px");
//    			simplePanel.clear();
//    			simplePanel.add(image);
//    			simplePanel.setVisible(true);               
            }
        });
		
		umpireSuggestBox.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
		    @Override
		    public void onSelection(SelectionEvent<Suggestion> event) {
		    	StringWithIdSuggestion selectedSuggestion = (StringWithIdSuggestion) event.getSelectedItem();
		    	presenter.getUmpireById(selectedSuggestion.getId());
		    }
		});

	}

	private void postInit() {
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public Presenter getPresenter() {
		return presenter;
	}

	@Override
	public void setValues(UmpireDTO dto) {
		this.umpire = dto;
		lastName.setText(umpire.getLastName());
		firstName.setText(umpire.getFirstName());
		city.setText(umpire.getCity());
		email.setText(umpire.getEmail());
		gsm.setText(umpire.getGsm());
		club.setText(umpire.getClub());
		birthDate.setText(umpire.getBirthDate());
		ranking.setText(umpire.getRanking());
		hiddenumpireId.setValue(umpire.getId().toString());
		if (umpire.getImageData() != null) {
			Image image = new Image(umpire.getImageData());
			image.setHeight("250px");
			simplePanel.clear();
			simplePanel.add(image);
			simplePanel.setVisible(true);
		} else {
			simplePanel.setVisible(false);
		}
		
	}

	@Override
	public void updateUmpireList(List<UmpireDTO> umpiresDTOList) {
		List<StringWithIdSuggestion> list = new ArrayList<StringWithIdSuggestion>();
		for (UmpireDTO umpireDTO : umpiresDTOList) {
			StringWithIdSuggestion idSuggestion = new StringWithIdSuggestion(umpireDTO.getId(),umpireDTO.getLastName() +" " +umpireDTO.getFirstName());			
			list.add(idSuggestion);
		}
		oracle.setSuggestions(list);

	}

	@Override
	public UmpireDTO getUmpire() {
		return umpire;
	}

	class DynamicSuggestOracle extends MultiWordSuggestOracle {

		private List<StringWithIdSuggestion> umpireWithIds = new ArrayList<StringWithIdSuggestion>();

		public DynamicSuggestOracle() {
			super();
		}

		@Override
		public void requestSuggestions(SuggestOracle.Request req, SuggestOracle.Callback callback) {
			//super.requestSuggestions(req, callback);
			// receive the query and return the list of suggestions to display
			List<StringWithIdSuggestion> suggestionsToDisplay = new ArrayList<StringWithIdSuggestion>();
			for (StringWithIdSuggestion suggestion : umpireWithIds) {
				if (suggestion.getDisplayString().toLowerCase()
						.contains(req.getQuery().toLowerCase())) {
					suggestionsToDisplay.add(suggestion);
				}
			}
			callback.onSuggestionsReady(req, new Response(suggestionsToDisplay));

		}

		public void setSuggestions(List<StringWithIdSuggestion> studWithIds) {
			this.umpireWithIds = studWithIds;
		}
	}

	@Override
	public void setUmpire(UmpireDTO dto) {
		this.umpire = dto;
		fullName.setText(umpire.getFirstName() +" " + umpire.getLastName());
		//if (umpire.getId()==29) {
			uploadForm.setVisible(true);
		//}
		
		
	}

}

